<template>
  <div class="container">
    <el-form
      :inline="true"
      :model="partnerform1"
      ref="partnerform1"
      class="demo-form-inline"
    >
      <el-form-item label="商品类型搜索">
        <el-input v-model="partnerform1.name" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button
          @click="newAndChange('新建')"
          size="mini"
          icon="el-icon-circle-plus-outline"
          style="background-color: #ff8437; color: #fff"
          >新建</el-button
        >
         <el-button
          size="mini"
          style="background-color: #fbf4f0; color: #000"
          @click="importdata"
          >导入数据</el-button
        >
      </div>
      <el-table :data="skuList">
        <!-- 放置列 -->
        <el-table-column
          prop="index"
          align="center"
          width="50px"
          label="序号"
        />
        <el-table-column prop="skuName" align="start" label="商品名称" />
         <el-table-column align="center" label="设备图片">
          <template v-slot="{ row }">
            <el-avatar :size="30" :src="row.skuImage" />
          </template>
        </el-table-column>
        <el-table-column prop="brandName" align="start" label="品牌" />
        <el-table-column prop="unit" align="start" label="规格" />
        <el-table-column prop="price" align="start" label="商品价格" />
        <el-table-column prop="classId" align="start" label="商品类型">
          <template v-slot="{ row }">
             {{classobj[row.classId]}}
            </template>
        </el-table-column>
        <!-- this.changvmobj.updateTime1=row.updateTime.replace('T',' ') -->
        <el-table-column prop="createTime" align="start" label="创建日期" >
            <template v-slot="{ row }">
              {{row.updateTime.replace('T',' ')}}
            </template>
          </el-table-column>
        <el-table-column align="center" width="100px" label="操作">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <el-button
              size="mini"
              type="text"
              @click="newAndChange('修改', row)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row
       v-if="this.totalpage>1"
        type="flex"
        style="height: 60px"
        align="middle"
        justify="space-between"
      >
        <el-col :span="12"
          ><span style="font-size: 13px; color: #999; padding-left: 12px"
            >共{{ totalcount }}条记录 第{{ pageParams.pageIndex }}/{{
              totalpage
            }}页</span
          ></el-col
        >
        <el-col :push="12">
          <el-button-group>
            <el-button
              type="primary"
              @click="innPage"
              size="mini"
              :disabled="pageParams.pageIndex == 1"
              icon="el-icon-arrow-left"
              style="
                background-color: #d5ddf8;
                color: #000;
                margin-right: 12px;
                border: none;
              "
              >上一页</el-button
            >
            <el-button
              type="primary"
              @click="addPage"
              size="mini"
              :disabled="pageParams.pageIndex == this.totalpage"
              style="background-color: #d5ddf8; color: #000; border: none"
              >下一页<i class="el-icon-arrow-right el-icon--right"></i
            ></el-button>
          </el-button-group>
        </el-col>
      </el-row>

    </div>
      <!-- 新增商品的dialog -->
      <el-dialog
        :title="models"
        :visible.sync="dialogFormVisible"
        @close="closefn"
      >
        <el-form
          :model="addPartnerForm"
          :rules="rules"
          label-width="110px"
          ref="partnerform"
        >
          <el-form-item label="商品名称" prop="skuName">
            <el-input
              v-model="addPartnerForm.skuName"
              maxlength="15"
              show-word-limit
              placeholder="请输入"
            ></el-input>
          </el-form-item>
           <el-form-item label="品牌" prop="brandName">
            <el-input
              v-model="addPartnerForm.brandName"
              maxlength="10"
              show-word-limit
              placeholder="请输入"
            ></el-input>
          </el-form-item>
           <el-form-item label="商品价格（）" prop="price">
            <el-input-number
              v-model="addPartnerForm.price"
              controls-position="right"
              placeholder="请输入"
              style="width:95%;display: flex; flex-direction: column"
            >
            </el-input-number>
          </el-form-item>
           <el-form-item label="商品类型" prop="classId">
           <el-select
              style="width:95%"
              v-model="addPartnerForm.classId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in classlist"
                :key="item.classId"
                :value="item.classId"
                :label="item.className"
              ></el-option>
            </el-select>
          </el-form-item>
           <el-form-item label="规格" prop="unit">
            <el-input
              v-model="addPartnerForm.unit"
              maxlength="10"
              show-word-limit
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :http-request="myRequest"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="addPartnerForm.skuImage"
                :src="addPartnerForm.skuImage"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过100kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="quitfn">取 消</el-button>
          <el-button type="primary" @click="submitfn">确 定</el-button>
        </div>
      </el-dialog>

      <ImportExcel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getSku"
    />
  </div>
</template>
<script>
import {
  getallSkuclass,
  getSku,
  addSku,
  changeSku,
} from "@/api/sku";
import ImportExcel from './uploadskumsg.vue'
import { uploadimage } from '@/api/mechian'
export default {
  name: "Node",
  components: {
    ImportExcel
  },
  data() {
    return {
      models: "新建",
      showExcelDialog:false,
      dialogFormVisible: false,
      totalcount: "",
      totalpage: "",
      pageParams: {
        pageIndex: 1,
        pageSize: 10,
      },
      addPartnerForm: {
        brandName: "",
        classId: "",
        price: "",
        skuImage: "",
        skuName: "",
        unit: "",
      },
      partnerform1: {
        name: "",
      },
      nodelist: {},
      classlist:[],
      classobj:{},
      skuList: [],
      rules: {
        brandName:[{required: true,message:'请输入品牌名称'}],
        classId:[{required: true,message:'请选择商品类型'}],
        price:[{required: true,message:'请输入商品价格'}],
        skuImage:[{required: true,message:'请上传商品图片'}],
        skuName:[{required: true,message:'请输入商品名称'}],
        unit:[{required: true,message:'请输入商品规格'}],
      },
    };
  },
  async created() {
  this.getSku();
  const res =  await getallSkuclass()
  this.classlist= res.currentPageRecords
  this.classobj= this.classlist.reduce((acc, cur) => {
  acc[cur.classId] = cur.className;
  return acc;
}, {});
  },
  methods: {
    //导入数据
    importdata(){
      this.showExcelDialog=true
    },
   // 覆盖原有的请求，改为自己的上传
    async myRequest({ file }) {
      try {
        const myPic = new FormData()
        myPic.set('fileName', file)
        const res = await uploadimage(myPic)
        console.log(res)
        // 发送成功后进行图片的回显
      this.addPartnerForm.skuImage = res
      } catch (error) {
        console.log(error)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = [
        "image/jpeg",
        "image/png"
      ].includes(file.type);
      const isLt100k = file.size / 1024 < 100; // 100k

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG PNG 格式!");
      }
      if (!isLt100k) {
        this.$message.error("上传头像图片大小不能超过 100kb!");
      }
      return isJPG && isLt100k;
    },
    //下一页
    addPage() {
      this.pageParams.pageIndex++;
      this.getSku();
    },
    // 上一页
    innPage() {
      this.pageParams.pageIndex--;
      this.getSku();
    },
    async getSku() {
      const res = await getSku(
        this.pageParams.pageIndex,
        this.pageParams.pageSize,
        this.partnerform1.name
      );
      this.skuList = res.currentPageRecords;
      this.totalpage = res.totalPage;
      this.totalcount = res.totalCount;
      this.skuList.forEach((item, index) => {
        this.$set(
          item,
          "index",
          this.pageParams.pageSize * (this.pageParams.pageIndex - 1) + index + 1
        );
      });
    },
    search() {
      this.getSku();
    },
    closefn() {
      this.$refs.partnerform.resetFields();
      this. addPartnerForm={
        brandName: "",
        classId: "",
        price: "",
        skuImage: "",
        skuName: "",
        unit: "",
      }
      this.dialogFormVisible = false
    },
    quitfn() {
      this.closefn();
    },
    submitfn() {
      this.$refs.partnerform.validate(async (right) => {
        if (right) {
          if (!this.addPartnerForm.skuId) {
            await addSku(this.addPartnerForm);
            this.$message.success("添加成功");
            this.pageParams.pageIndex = 1;
            this.getSku();
            this.closefn();
          } else {
            const res = await changeSku(
              this.addPartnerForm,
              this.addPartnerForm.skuId
            );
            if (res == true) {
              this.$message.success("修改成功");
              this.closefn();
              this.getSku();
            }
          }
        } else {
          this.$message.error(new Error());
        }
      });
    },
    //新建and修改
    async newAndChange(model, row) {
      if (model == "新建") {
        this.models = '新增商品';
        this.dialogFormVisible = true;
      } else {
        this.models = '修改商品';
        console.log(row);
        this.addPartnerForm.brandName = row.brandName;
        this.addPartnerForm.classId = row.classId;
        this.addPartnerForm.price = row.price;
        this.addPartnerForm.skuImage = row.skuImage;
        this.addPartnerForm.skuName = row.skuName;
        this.addPartnerForm.unit = row.unit;
        this.addPartnerForm.skuId = row.skuId;
        this.dialogFormVisible = true;
      }
    },
  //  async del(row) {
  //   this.$confirm('确认删除？').then(
  //    async()=>{ 
  //   await delSkuType(row.skuId)
  //   if(this.skuList.length===1){this.pageParams.pageIndex--}
  //   this.getSku()
  //     })
  //   },
  },
};
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
::v-deep .el-dialog {
  border-radius: 10px;
  padding: 20px;
  width: 50%;
  .dialog-footer {
    margin-top: -30px;
  }
  .area {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
  }
  .title {
    width: 50%;
    margin-bottom: 20px;
    .right {
      width: 80%;
      margin-left: 10px;
      .el-table {
        margin-top: -15px;
      }
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #dd2626;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>
